#region Usings

using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using RailNet.Dao.Entity;

#endregion

namespace RailNet.Dao.Repository
{
    public class RelationRepository : IRelationRepository
    {
        private readonly RailnetContext _context = new RailnetContext();

        #region IRelationRepository Members

        public IQueryable<Relation> All
        {
            get { return _context.Relations; }
        }

        public IQueryable<Relation> AllIncluding(params Expression<Func<Relation, object>>[] includeProperties)
        {
            IQueryable<Relation> query = _context.Relations;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public IQueryable<Relation> AllWithDefaultIncluding()
        {
            IQueryable<Relation> query = _context.Relations;
            query = query.Include("Descriptions").Include("Descriptions.Station").Include("RelationRus").Include("RelationRus.Ru");
            return query;
        }

        public Relation Find(long id)
        {
            return _context.Relations.Find(id);
        }

        public void InsertOrUpdate(Relation relation)
        {
            if (relation.Id == default(long))
            {
                // New entity
                _context.Relations.Add(relation);
            }
            else
            {
                // Existing entity
                _context.Entry(relation).State = EntityState.Modified;
            }
        }

        public void Delete(long id)
        {
            var relation = _context.Relations.Find(id);
            _context.Relations.Remove(relation);
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        #endregion
    }
}